package com.tang.module.system.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tang.common.constant.cahce.BusinessCacheConstant;
import com.tang.common.constant.BusinessConstant;
import com.tang.common.exception.GlobalException;
import com.tang.common.utils.CommonUtils;
import com.tang.common.resources.TaoPage;
import com.tang.module.system.service.SystemInfoService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 系统信息接口
 * @author tang
 * @date 2022/1/24 10:57
 */
@Service
public class SystemInfoServiceImpl implements SystemInfoService {


    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Value("${system.redisToken}")
    private Boolean redisToken;

    @Override
    public Page<Object> onlineUsers(TaoPage taoPage) {
        //获取登录信息全部key
        //redis中存储的数据类型为map
        Set<String> keys = redisTemplate.keys(BusinessConstant.LIST_OF_ONLINE_PEOPLE + "*");
        //无数据
        if (keys == null){
            return CommonUtils.pageUtli(null,taoPage.getCurrent(),taoPage.getSize());
        }
        List<Object> list = new ArrayList<>();
        for (String key : keys) {
            list.add(redisTemplate.opsForValue().get(key));
        }
        return CommonUtils.pageUtli(list,taoPage.getCurrent(),taoPage.getSize());
    }

    @Override
    public Boolean offline(String account) {
        if (! redisToken){
            throw  new GlobalException("当前登录信息未存储在Redis中,无法执行此操作");
        }
        return redisTemplate.delete(BusinessCacheConstant.TOKEN_PREFIX + account);
    }
}
